import upload from "./upload.js"
fetch("sportsman-add.html").then(r => r.text()).then(text => {
	let sportsmanaddDialog = $(text);
	$("body").append(sportsmanaddDialog);

	let form = sportsmanaddDialog[0].querySelector("form");//form是原生标签元素，非jquery对象
	let btn = sportsmanaddDialog[0].querySelector("._save");
	
	let countryCode = form.countryCode;
	
	fetch("country-list.let").then(r=>r.json()).then(data=>{
		data.forEach(item=>{
			countryCode.add(new Option(item.countryName,item.countryCode));
		});
	});
	
	upload(sportsmanaddDialog.find("._upload")[0],function(data){
		form.sportsmanUri.value = data.uri;
	})

	btn.onclick = function() {
		//验证输入参数
		let param = new URLSearchParams(new FormData(form));
		console.info(param.toString());
		fetch("Sportsman-add.let", {
			method: 'POST',
			mode: 'cors',
			cache: 'no-cache',
			credentials: 'include',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded',
			},
			redirect: 'follow',
			referrerPolicy: 'no-referrer',
			body: param
		}).then(r => r.json()).then(data => {
			if (data.ok) {
				sportsmanaddDialog.modal('hide');
				form.reset();
				window.postMessage("loadData");//发送消息
			} else {
				alert(data.msg);
			}
			console.debug(data);
		}).catch(e => {
			console.error(e);
		});
	}
});

export default function() {
	window.postMessage("loadData");
}